package com.mattcofer.cartoonwidget;

import com.mattcofer.cartoonwidget.CartoonProvider;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import com.mattcofer.cartoonwidget.CartoonProvider.Cartoons;
import com.mattcofer.cartoonwidget.CartoonProvider.CartoonsColumns;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore.Images;
import android.text.format.Time;
import android.util.Log;
import android.widget.RemoteViews;

import com.mattcofer.cartoonwidget.CartoonWidget;
import com.mattcofer.cartoonwidget.UpdateService;

public class CartoonWidget extends AppWidgetProvider {
	private static final String TAG = "CartoonWidget";

    private static final String[] PROJECTION_CARTOONS = new String[] {
        CartoonsColumns.URL, //URI of the image in the internal media library
    };
    
    private static final int COL_URL = 0;
	
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		// To prevent any ANR timeouts, we perform the update in a service
		context.startService(new Intent(context, UpdateService.class));
		
        // If no specific widgets requested, collect list of all
        if (appWidgetIds == null) {
            appWidgetIds = appWidgetManager.getAppWidgetIds(
                    new ComponentName(context, UpdateService.class));
        }

        // Request update for these widgets and launch updater service
        UpdateService.requestUpdate(appWidgetIds);
        context.startService(new Intent(context, UpdateService.class));

	}
	   
	@Override
	public void onEnabled(Context context)
	{
		Log.d(TAG, ".CartoonWidget$onEnabled");
	}
	
	/*
	 * See the link below regarding the bug in the onDeleted that requires this onRecieve override
	 * http://groups.google.com/group/android-developers/browse_thread/thread/365d1ed3aac30916/230dcd6d9adffbb6?lnk=gst&q=appwidget+deleted#230dcd6d9adffbb6
	 * (non-Javadoc)
	 * @see android.appwidget.AppWidgetProvider#onReceive(android.content.Context, android.content.Intent)
	 */
	@Override
	public void onReceive(Context context, Intent intent) {
	    final String action = intent.getAction();
	    if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
	        final int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
	        if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
	            this.onDeleted(context, new int[] { appWidgetId });
	        }
	    } else {
	        super.onReceive(context, intent);
	    }

	} 
	
    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        ContentResolver resolver = context.getContentResolver();
        Log.d(TAG, ".CartoonWidget$onDeleted deleting widget Ids: " + appWidgetIds.toString());
        for (int appWidgetId : appWidgetIds) {
            Uri appWidgetUri = ContentUris.withAppendedId(Cartoons.CONTENT_URI, appWidgetId);
            resolver.delete(appWidgetUri, null, null);
            Log.d(TAG, ".CartoonWidget$onDeleted deleted widget Uri: " + appWidgetUri.toString());
        }
        
        AppWidgetManager manager = AppWidgetManager.getInstance(context);
        int[] remainingAppWidgetIds = manager.getAppWidgetIds(new ComponentName(context, CartoonWidget.class));
        
        if (remainingAppWidgetIds.length==0)
        {
        	//TODO: the update service should be canceled here
        	Log.d(TAG, ".CartoonWidget$onDeleted deleted all widgets... zero remain on the desktop");
        }
    }
    
    //This will block until the online API returns.
    public static RemoteViews buildUpdate(Context context, Uri appWidgetUri) {
        Log.d(TAG, ".UpdateService$buildUpdate on Uri: " + appWidgetUri.toString());
        
    	//Initialize some variables
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.main_highlight);
        ContentResolver 	resolver = context.getContentResolver();
        boolean cartoonUpdated = false;

        Cursor cursor = null;

        //holds the uri of the image to be displayed for this update
        String uri = "";
        try
        {
        	Uri cartoonAtUri = Uri.withAppendedPath(appWidgetUri, Cartoons.TWIG_CARTOON_AT);
            Uri cartoonAtNowUri = Uri.withAppendedPath(cartoonAtUri, Long.toString(System.currentTimeMillis()));
            Log.d(TAG, ".UpdateService$buildUpdate cartoonAtUri = " + cartoonAtNowUri.toString());
            cursor = resolver.query(cartoonAtNowUri, PROJECTION_CARTOONS, null, null, null);
            if (cursor != null && cursor.moveToFirst())
            {
                uri = cursor.getString(COL_URI);
                views.setImageViewUri(R.id.image, Uri.parse(uri));
            }
            
            cartoonUpdated = true;
        
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
            
        // If not filled correctly, show error message and hide other fields
        if (!cartoonUpdated) {
            views = new RemoteViews(context.getPackageName(), R.layout.main_initial);
        }
        
		Intent viewCartoonIntent = null;
		if (uri!=null)
		{
            if (uri!=null)
            {
            	viewCartoonIntent = new Intent("com.mattcofer.cartoonwidget.VIEW_DILBERT", Uri.parse(uri), context, ViewCartoon.class);
            	viewCartoonIntent.putExtra("AppWidgetUri", appWidgetUri.toString());
            }
		}
    
        if (viewCartoonIntent!=null)
        {
        	PendingIntent pendingIntent = PendingIntent.getActivity(context,
        			0 /* no requestCode */, viewCartoonIntent, Intent.FLAG_ACTIVITY_NEW_TASK );
        	views.setOnClickPendingIntent(R.id.widget, pendingIntent);          
        }
        
        return views;        
        
    }

	
}
